//===============================================================================
// Microsoft Architecture Strategy Team
// LitwareHR - SaaS Sample Application
//===============================================================================
// Copyright  Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===============================================================================


//===============================================================================
// Microsoft Architecture Strategy Team
// LitwareHR - S+S Sample Application
//===============================================================================
// Copyright  Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===============================================================================

using System;
using System.Collections.Generic;
using System.Text;
using LitwareHR.PublicApp.WinUX.Constants;
using Microsoft.Practices.CompositeUI.EventBroker;
using Microsoft.Practices.ObjectBuilder;
using Microsoft.Practices.SmartClient.DisconnectedAgent;
using Microsoft.Practices.SmartClient.ConnectionMonitor;
using Microsoft.Practices.CompositeUI;
using Microsoft.Practices.SmartClient.EnterpriseLibrary;
using LitwareHR.Infrastructure.Interface;
using LitwareHR.Infrastructure.Interface.Constants;

namespace LitwareHR.PublicApp.WinUX.Services
{
    public class RequestsManagerService
    {
        [EventPublication(EventTopicNames.RequestQueueChanged, PublicationScope.Global)]
        public event EventHandler<EventArgs> RequestQueueChanged;
    
        [EventPublication(EventTopicNames.ConnectionStatusChanged, PublicationScope.Global)]
        public event EventHandler<EventArgs> ConnectionStatusChanged;

        [EventPublication(EventTopicNames.StatusUpdate, PublicationScope.Global)]
        public event EventHandler<EventArgs> StatusUpdate;

        [EventPublication(EventTopicNames.OfflineRequestDispatched, PublicationScope.Global)]
        public event EventHandler<EventArgs> OfflineRequestDispatched;

        [EventPublication(EventTopicNames.RequestsQueueUpdated, PublicationScope.Global)]
        public event EventHandler<EventArgs> NotifyRequestQueueCount;

        [EventPublication(EventTopicNames.Disconnect, PublicationScope.Global)]
        public event EventHandler<EventArgs> Disconnect;

        [EventPublication(EventTopicNames.Connect, PublicationScope.Global)]
        public event EventHandler<EventArgs> Connect;
                      
  
        private RequestManager requestManager = null;
        WorkItem _workItem = null;

        [InjectionConstructor]
        public RequestsManagerService( [ServiceDependency] WorkItem workItem )
        {
            _workItem = workItem;

            // Setup request manager
            requestManager = DatabaseRequestManagerIntializer.Initialize();
            requestManager.StopAutomaticDispatch();
            
            //Monitor Requests Dispatching and Queueing
            requestManager.RequestDispatched += new EventHandler<RequestDispatchedEventArgs>(requestManager_RequestDispatched);
            requestManager.RequestQueue.RequestEnqueued += new EventHandler<RequestEnqueuedEventArgs>(RequestQueue_RequestEnqueued);
            requestManager.DeadLetterQueue.RequestEnqueued += new EventHandler<RequestEnqueuedEventArgs>(DeadLetterQueue_RequestEnqueued);
            // Setup the connection Monitor used by other services for managing network availability
            ConnectionMonitor connectionMonitor = ConnectionMonitorFactory.CreateFromConfiguration();

            // Assume for now only 1 network adapter & subscribe to status changes
            connectionMonitor.Networks[0].StateChanged += new EventHandler<Microsoft.Practices.SmartClient.ConnectionMonitor.StateChangedEventArgs>(ModuleController_StateChanged);

            FireConnectionStatusEvents(connectionMonitor.IsConnected);

            // Add the request queue to the Root WorkItem. This queue will be used
            // by service agents to enqueue requests.
            _workItem.RootWorkItem.Services.Add(requestManager.RequestQueue);
            _workItem.RootWorkItem.Services.Add<ConnectionMonitor>(connectionMonitor);
           
        }

        void DeadLetterQueue_RequestEnqueued(object sender, RequestEnqueuedEventArgs e)
        {
            OnRequestQueueChanged(null);
        }

        void RequestQueue_RequestEnqueued(object sender, RequestEnqueuedEventArgs e)
        {
            OnNotifyRequestsQueueCount();
            OnRequestQueueChanged(null);
        }

        public void StartDispatching()
        {
            requestManager.StartAutomaticDispatch();
        }

        void ModuleController_StateChanged(object sender, Microsoft.Practices.SmartClient.ConnectionMonitor.StateChangedEventArgs e)
        {
            ConnectionMonitor cm = _workItem.RootWorkItem.Services.Get<ConnectionMonitor>();
            bool status = cm.IsConnected;
            FireConnectionStatusEvents(status);
        }

        private void FireConnectionStatusEvents(bool IsConnected)
        {
            string connectionStatus = IsConnected ? "Online" : "Offline";
            OnStatusUpdate(new EventArgs<string>(connectionStatus));
            OnConnectionStatusChanged(new EventArgs<bool>(IsConnected));

            if (IsConnected)
                OnConnect(null);
            else
                OnDisconnect(null);
        }

        /// <summary>
        /// Notification of Requests being Dispatched
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void requestManager_RequestDispatched(object sender, RequestDispatchedEventArgs e)
        {
            OnOfflineRequestDispatched(new EventArgs<DispatchResult>(e.Result));
            OnNotifyRequestsQueueCount();
            OnRequestQueueChanged(null);
        }

        protected virtual void OnNotifyRequestsQueueCount()
        {
            if (NotifyRequestQueueCount != null)
            {
                NotifyRequestQueueCount(this, new EventArgs<int>(requestManager.RequestQueue.GetCount())); 
            }
        }


        protected virtual void OnStatusUpdate(EventArgs eventArgs)
        {
            if (StatusUpdate != null)
            {
                StatusUpdate(this, eventArgs);
            }
        }

        protected virtual void OnConnectionStatusChanged(EventArgs eventArgs)
        {
            if (ConnectionStatusChanged != null)
            {
                ConnectionStatusChanged(this, eventArgs);
            }
        }


        protected virtual void OnOfflineRequestDispatched(EventArgs eventArgs)
        {
            if (OfflineRequestDispatched != null)
            {
                OfflineRequestDispatched(this, eventArgs);
            }
        }

        public void MoveQueuedRequestToDeadLetterQueue(string tagName)
        {
            IRequestQueue requestQueue = requestManager.RequestQueue;
            IRequestQueue deadLetterQueue = requestManager.DeadLetterQueue;

            IEnumerable<Request> requestsByTag = requestQueue.GetRequests(tagName);

            foreach (Request request in requestsByTag)
            {                 
                requestQueue.Remove(request);
                deadLetterQueue.Enqueue(request); 
            }            
        }

        public IRequestQueue DeadQueue
        {
             get{
                return requestManager.DeadLetterQueue;
             }
        }

        public IRequestQueue RequestQueue
        {
            get
            {
                return requestManager.RequestQueue;
            }
        }

        protected virtual void OnRequestQueueChanged(EventArgs eventArgs)
        {
            if (RequestQueueChanged != null)
            {
                RequestQueueChanged(this, eventArgs);
            }
        }

        protected virtual void OnConnect(EventArgs eventArgs)
        {
            if (Connect != null)
            {
                Connect(this, eventArgs);
            }
        }

        protected virtual void OnDisconnect(EventArgs eventArgs)
        {
            if (Disconnect != null)
            {
                Disconnect(this, eventArgs);
            }
        }
    }
}
